import { defineStore } from 'pinia'
import { apiURL, apiGetData } from '@/api'

let refreshTimer: number | null

const useSysMsgStore = defineStore('sys-msg', {
  state: () => ({
    msgs: [] as any[]
  }),
  getters: {
    unReadMsgs(): Array<any> {
      return this.msgs.filter((o: any) => {
        return o.status === -1
      })
    },
    unReadCount(): number {
      return this.unReadMsgs.length
    },
    unReadCountText() {
      if (this.unReadCount < 1) {
        return ''
      } else if (this.unReadCount > 99) {
        return '99+'
      } else {
        return '' + this.unReadCount
      }
    }
  },
  actions: {
    getSysMsgs(data = { page: 1, limit: 100, offset: 0 }) {
      if (refreshTimer) {
        clearTimeout(refreshTimer)
        refreshTimer = null
      }
      return apiGetData(apiURL.sysMsg, {
        status: -1,
        ...data
      })
        .then((resp) => {
          const { list = [] } = resp.data
          this.msgs = list
        })
        .finally(() => {
          if (refreshTimer) {
            return
          }
          refreshTimer = setTimeout(() => {
            refreshTimer = null
            this.getSysMsgs(data)
          }, 60000)
        })
    }
  }
})

export default useSysMsgStore
